<template>
  <a-spin :spinning="doActionLoading" tip="正在处理....">
    <div
      class="home-container"
      :style="{ overflow: doActionLoading ? 'hidden' : '' }"
    >
      <template>
        <HomeHeader
          :skeleton-loading="skeletonLoading"
          :home-header-subject="homeHeaderSubject"
        />
      </template>

      <a-spin tip="正在加载中..." :spinning="false">
        <template>
          <HomeContent
            :parent-change="parentChange"
            :skeleton-loading="skeletonLoading"
            :ant-list="Dep ? DepAntList : antList"
            :history="history"
            :default-padding-bottom="defaultPaddingBottom"
            :default-title="homeHeaderSubject.title"
            :filePageList="filePageList"
            @downFile="downFile($event)"
          />
        </template>
        <template>
          <HomeFoot
            v-if="toDoAction || toDoAction === 'true'"
            :foot-group="footGroup"
          />
        </template>
      </a-spin>
      <template>
        <a-modal
          v-model="asyncSuccess"
          :keyboard="false"
          :closable="false"
          :footer="null"
        >
          <a-result
            :status="'success'"
            title="操作成功!"
            :sub-title="`受理单号: ${this.parameterData.formGuid}.`"
          >
            <template #extra>
              页面将在:
              <a-statistic-countdown
                @finish="handledSubmit"
                :value="constNumber"
              />
              秒后关闭
            </template>
          </a-result>
        </a-modal>
      </template>

      <!-- <template>
        <HandlerAction
          @tagClick="tagClick($event)"
          :tagList="tagList"
          :handleActionVisible="handleActionVisible"
          :actionModel="actionModel"
          @ok="ok"
          @cancel="cancel"
          @afterClose="afterClose"
          @nodeUsersChange="nodeUsersChange($event)"
        />
      </template> -->
    </div>
  </a-spin>
</template>

<script lang="ts">
import { Component, Vue, Watch } from "vue-property-decorator";
import HomeHeader from "@/views/home/HomeHeader.vue";
import HomeFoot from "@/views/home/HomeFoot.vue";
import HomeContent from "@/views/home/HomeContent.vue";
// import { HandlerAction } from "@/components";
// import loadingType from '@/views/DetailPage/mixinsloadingtype'

import {
  mockUrl,
  taskFindFormGuid,
  getInstanceOpinion,
  taskDoAction,
  DoActionProp,
  modifyStatus,
  queryHeader,
  handleNodeFreeUser,
  filePage,
  getCanBackHistoryNodes,
} from "@/api/login/login.ts";
import { removeToken } from "@/utils/utils";
import * as dd from "dingtalk-jsapi";
import _ from "lodash";
import { notification } from "ant-design-vue";
import { BASE_URL, KK_URL } from "@/utils/utils.ts";
@Component({
  name: "Home",
  components: {
    HomeHeader,
    HomeFoot,
    HomeContent,
    // HandlerAction,
  },
})
export default class Home extends Vue {
  public filePageList: Array<any> = [];

  public handleNodeAction = {
    action: "start",
    businessKey: "",
    data: {},
    defId: this.$route.query.defId as string,
    extendConf: { nodeId: "" },
    taskId: this.$route.query.taskId as string,
    nodeId: this.$route.query.nodeId as string,
  };

  public fileHandler = {
    guid: this.$route.query.formGuid as string,
    status: "",
    type: this.$route.query.fileType as string,
  };

  public tagList: string[] = [
    "同意",
    "拟同意",
    "请注意，情况复杂!",
    "情况紧急，请尽快处理!",
  ];
  // public showSPBtns = this.$route.query["showSPBtns"] as string;
  public handleActionVisible = false;

  public actionModel: {
    nodeUsers: string | undefined;
    destination: string[];
    nodeNameMap: {
      [key: string]: any;
    };
    nodeIdentitysMap: {
      [key: string]: any;
    };
    nodeList: {
      [key: string]: any;
    };
    meno: string;
  } = {
    nodeUsers: "",
    destination: [],
    nodeNameMap: {},
    nodeIdentitysMap: {},
    nodeList: {},
    meno: "",
  };

  public tableId: string | number = this.$route.query.tableId as string;

  public asyncSuccess = false;

  public doActionLoading = false;

  public skeletonLoading = true;

  public parameterData = {
    subject: "",
    title: "",
    sId: "",
    bizKey: "",
    defId: "",
    instId: "",
    flag: "",
    fileType: "",
    nsukey: "",
    formGuid: "",
    createTime: "",
  };
  /**
   * 这里不做限制根据实际需求将homeHeaderSubject里面的名字换成后台返回的键名就行了然后去组件里面改掉
   */
  public homeHeaderSubject = {
    title: "title",
    iconTitle: sessionStorage.getItem("userIdentity"),
    name: "subject",
    numbering: "formGuid",
    createTime: "createTime",
  };
  /**
   * 这里做了限制不要修改title,title是必须的其他都是可选, class最好也不要改
   */
  public footGroup = [
    {
      title: "通过",
      class: "through",
      type: "",
      _: "through",
    },
    {
      title: "驳回",
      _: "turnDown",
      class: "turnDown",
    },
    {
      title: "废弃",
      class: "abandoned",
      type: "danger",
      _: "abandoned",
    },
  ];
  /**
   * 最外层数据
   */
  public antList: Array<any> = [];

  public DepAntList: Array<any> = [];

  public defaultPaddingBottom = 0;

  public history = [];

  public doAction: DoActionProp = {
    sId: this.$route.query["sid"] as string,
    businessKey: "",
    data: {
      test: "jeff",
    },
    test: "jeff",
    formType: "FRAME",
    action: "agree",
    defId: this.$route.query["defId"] as string,
    id: this.$route.query["id"] as string,
    formGuid: this.$route.query["formGuid"] as string,
    nodeId: "",
    instId: this.$route.query["instId"] as string,
    defKey: this.$route.query["defKey"] as string,
    taskId: this.$route.query["taskId"] as string,
    instanceId: "",
    destination: "",
    nodeUsers: {},
  };

  public constNumber = Date.now() + 1000 * 3;

  public Dep = false;
  public isDrawerShow = false;
  public targetFileNow: any = {};
  @Watch("skeletonLoading")
  setHeight() {
    this.$nextTick(() => {
      this.clientHeight();
    });
  }

  async created() {
    function filterArray(list, data) {
      for (const i in data) {
        for (let j = 0; j < list.length; j++) {
          if (list[j].children) {
            filterArray(list[j].children, data);
          } else {
            if (list[j].field === i) {
              list[j].vNodeSpan = data[i];
            }
          }
        }
      }
    }
    function filterArrayList(list, data) {
      for (const i in data) {
        for (const j in list) {
          if (j === "children") {
            list[j] = list[j].map((item) =>
              Object.assign({}, filterArrayList({ ...item }, data))
            );
          } else {
            if (j === "field" && list[j] === i) {
              list = { vNodeSpan: data[i], ...list };
            }
          }
        }
      }
      return list;
    }

    const getArray = async (data) => {
      const ArrayList: any = {};
      let AntListArray: Array<any> = [];
      let NewAntListArray: Array<any> = [];
      let NewArrayList: Array<any> = [];
      if (_.isArray(data)) {
        for (let j = 0; j < this.antList.length; j++) {
          if (this.antList[j].children) {
            AntListArray = AntListArray.concat({ ...this.antList[j] });
            this.antList.splice(j, 1);
          }
        }
        for (let i = 0; i < data.length - 1; i++) {
          AntListArray = AntListArray.concat({ ...AntListArray[0] });
        }
        AntListArray.forEach((item, index) => {
          item.listIndex = index;
          NewAntListArray[index] = Object.assign(
            {},
            filterArrayList({ ...item }, data[index])
          );
        });
        this.DepAntList = _.concat(this.antList, NewAntListArray);
      } else {
        for (let i = 0; i < Object.keys(data).length; i++) {
          if (_.isArray(data[Object.keys(data)[i]])) {
            for (let j = 0; j < this.antList.length; j++) {
              if (this.antList[j].field === Object.keys(data)[i]) {
                AntListArray = AntListArray.concat({ ...this.antList[j] });
                await this.antList.splice(j, 1);
              }
            }
            data[Object.keys(data)[i]].forEach((item) => {
              NewArrayList = NewArrayList.concat({ ...item });
            });
            ArrayList[Object.keys(data)[i]] = data[Object.keys(data)[i]];
          }
        }

        for (const i in ArrayList) {
          for (let j = 0; j < ArrayList[i].length; j++) {
            for (let z = 0; z < AntListArray.length; z++) {
              if (AntListArray[z].field === i) {
                NewAntListArray = NewAntListArray.concat({
                  ...AntListArray[z],
                });
              }
            }
          }
        }
        await NewArrayList.forEach((item, index) => {
          NewAntListArray[index].listIndex = index;
          filterArrayList(NewAntListArray[index], item);
        });
        await NewAntListArray.forEach((item) => {
          this.antList = this.antList.concat(item);
        });
      }
    };

    await queryHeader({ tableId: this.tableId }).then((res) => {
      if (!res.success) {
        console.error(res.detail);
        // this.$message.warning(res.message);
      }
      const { data } = res;
      this.antList = Object.assign([], data) || Object.assign({}, data);
    });

    await mockUrl().then(async () => {
      for (const i in this.parameterData) {
        this.parameterData[i] = this.$route.query[i];
        for (const j in this.homeHeaderSubject) {
          if (i === this.homeHeaderSubject[j]) {
            this.homeHeaderSubject[j] = this.parameterData[i];
          }
        }
      }
    });

    await taskFindFormGuid(
      `/${this.$route.query["responseUrl"]}/findByFormGuid`,
      { formGuid: this.parameterData.formGuid }
    ).then(async (res: any) => {
      if (res.success) {
        const sid = this.$route.query.sid;
        if (sid === "ryqxbgTable") {
          localStorage.setItem("tabledata", JSON.stringify(res.data));
        }
        const { data } = res;
        if (_.isArray(data)) {
          this.Dep = true;
          this.doAction.id = data[0].id;
          this.doAction.formGuid = data[0].formGuid;
          await getArray(data);
          await filterArray(this.antList, data[0]);
        } else {
          this.Dep = false;
          this.doAction.id = data.id;
          this.doAction.formGuid = data.formGuid;
          await getArray(data);
          await filterArray(this.antList, data);
        }
        this.skeletonLoading = false;
        this.$emit("loadingType", false);
      } else {
        console.error('获取信息失败')
        // this.$router.push({
        //   path: "/",
        // });
        // this.$message.error("获取信息失败!!!");
      }
    });
  }

  mounted() {
    this.$emit("loadingType", true);

    this.$nextTick(() => {
      if (this.skeletonLoading) return;
      this.clientHeight();
    });
  }

  tagClick(tag: string) {
    this.actionModel = {
      ...this.actionModel,
      meno: tag,
    };
  }
  actionClick({ file, record }: any) {
    // this.$message.success('文件操作')
    this.isDrawerShow = true;
    this.targetFileNow = file;
    // console.log(file, record)
  }
  async parentChange(e: any) {
    if (e === "1" || e === 1) {
      return false;
    } else if (e === "3" || e === 3) {
      filePage({ ...this.fileHandler }).then((res: any) => {
        if (res.success) {
          const { data } = res;
          this.filePageList = data;
        } else {
          this.filePageList = [];
        }
      });
    } else {
      await this.parentChange(3);

      await getInstanceOpinion({
        instId: this.$route.query["instId"] as string,
      }).then((res: any) => {
        if (res.success) {
          const nameArr = new Map();
          console.log(this.filePageList);
          if (this.filePageList && this.filePageList.length) {
            this.filePageList.forEach((item: any) => {
              item.fileName = item.originName;
              if (nameArr.has(item.trueName)) {
                nameArr.get(item.trueName).push(item);
              } else {
                nameArr.set(item.trueName, [item]);
              }
            });
          }
          if (res.data && res.data.length) {
            res.data = res.data.filter(
              (item: any) => item.taskName !== "起草节点"
            );
            res.data.forEach((item: any) => {
              if (item) {
                const { approverName, assignInfo1 } = item;
                const trueName = approverName || assignInfo1;
                if (nameArr.has(trueName)) {
                  item.fileList = nameArr.get(trueName);
                }
                if (!item.approverName) {
                  if (item.assignInfo) {
                    const reg = /[\u4e00-\u9fa5]+/g;
                    const re = item.assignInfo.match(reg);
                    if (re && re.length) {
                      item.approverName = re.toString();
                    }
                  }
                }
              }
            });
          }
          this.history = res.data;
        }
      });
    }
  }

  clientHeight() {
    const homeFoot = document.querySelector(".home-foot") as HTMLElement;
    const { clientHeight } = homeFoot ? homeFoot : { clientHeight: 0 };
    this.defaultPaddingBottom = clientHeight;
  }

  async handledSubmit() {
    await removeToken();
    dd.ready(() => {
      dd.biz.navigation.close({
        onSuccess: function() {
          console.log("退出成功");
        },
      });
    });
    dd.error(() => {
      window.close();
    });
    // window.opener = void
    // (window as any).open(' ', '_self')
  }

  handlerAction() {
    const { action } = this.handleNodeAction;
    if (action === "reject") {
      getCanBackHistoryNodes({
        taskId: this.$route.query.taskId as string,
      }).then((res: any) => {
        if (res.success) {
          const { data } = res;
          const list = {};

          for (const i in data) {
            list[i] = [
              {
                name: data[i],
              },
            ];
          }
          this.actionModel = {
            ...this.actionModel,
            nodeNameMap: data,
            nodeIdentitysMap: list,
          };
          this.handleActionVisible = true;
        } else {
          this.actionModel = {
            ...this.actionModel,
            nodeNameMap: {
              UserTask1: "起草节点",
            },
            nodeIdentitysMap: {
              UserTask1: [
                {
                  name: "起草节点",
                },
              ],
            },
          };
          this.handleActionVisible = true;
        }
      });
    } else {
      handleNodeFreeUser({ ...this.handleNodeAction }).then(
        async (res: any) => {
          if (res.success) {
            const { freeSelectNode, nodeNameMap, nodeIdentitysMap } = res.data;
            const { action } = this.doAction;
            if (freeSelectNode) {
              this.actionModel = {
                ...this.actionModel,
                nodeNameMap,
                nodeIdentitysMap,
              };
            } else {
              if (action === "reject") {
                this.actionModel = {
                  ...this.actionModel,
                  nodeNameMap: {
                    UserTask1: "起草节点",
                  },
                  nodeIdentitysMap: {
                    UserTask1: [
                      {
                        name: "起草节点",
                      },
                    ],
                  },
                };
              }
            }
            this.handleActionVisible = true;
          }
        }
      );
    }
  }

  downFile(item: { [key: string]: any }) {
    dd.biz.util.downloadFile({
      url: item.path,
      name: item.originName,
    });
  }

  nodeUsersChange(e) {
    const { target } = e;
    const { value } = target;
    this.actionModel = {
      ...this.actionModel,
      nodeList: this.actionModel.nodeIdentitysMap[value],
      destination: [],
    };
  }

  async ok() {
    const { nodeUsers, destination, nodeNameMap } = this.actionModel;
    if (destination.length === 0 && Object.keys(nodeNameMap).length > 0) {
      this.$message.warning("请选择分支人员");
    } else {
      this.handleActionVisible = false;
      this.doActionLoading = true;
      await taskDoAction({
        ...this.doAction,
        nodeUsers: { [nodeUsers as string]: destination },
        destination: nodeUsers as string,
      })
        .then((res: any) => {
          if (res.success) {
            this.constNumber = Date.now() + 1000 * 3;
            this.asyncSuccess = true;
          } else {
            console.error(res.message);
            // this.$message.error(res.message);
          }
          setTimeout(() => {
            this.doActionLoading = false;
          }, 500);
        })
        .catch((error) => {
          this.$message.error(error);
        });
    }
  }

  cancel() {
    this.actionModel = {
      nodeUsers: "",
      destination: [],
      nodeNameMap: {},
      nodeIdentitysMap: {},
      nodeList: {},
      meno: "",
    };
    this.handleActionVisible = false;
  }

  afterClose() {
    this.actionModel = {
      nodeUsers: "",
      destination: [],
      nodeNameMap: {},
      nodeIdentitysMap: {},
      nodeList: {},
      meno: "",
    };
  }

  async through() {
    this.doAction = { ...this.doAction, action: "agree" };
    this.handleNodeAction = { ...this.handleNodeAction, action: "agree" };
    this.tagList = [
      "同意",
      "拟同意",
      "请注意，情况复杂!",
      "情况紧急，请尽快处理!",
    ];
    await this.handlerAction();
  }

  async turnDown() {
    this.doAction = { ...this.doAction, action: "reject" };
    this.handleNodeAction = { ...this.handleNodeAction, action: "reject" };
    this.tagList = ["请补充相关附件!", "请修改相关数据!", "按单位要求退回!"];
    await this.handlerAction();
  }

  abandoned() {
    this.handleActionVisible = true;
    this.doActionLoading = true;
    modifyStatus("financialFund", {
      formGuid: this.parameterData.formGuid,
      status: "-1",
    }).then((res: any) => {
      this.constNumber = Date.now() + 1000 * 3;
      this.asyncSuccess = true;
      if (res.success) {
        this.asyncSuccess = true;
      }
      setTimeout(() => {
        this.doActionLoading = false;
      }, 500);
    });
  }

  get toDoAction() {
    return this.$route.query["doAction"];
  }
}
</script>

<style scoped lang="scss">
.home-container {
  display: flex;
  flex-direction: column;
  overflow: auto;
  background: #f0f2f5;
}
</style>
